var constMinZoom = 6;
var map;
var index = 0;
var markersArray = [];
var panoramioArray = [];
var geocoder;
var panoramioWaitTimerID;
var currentInfoWindow;

/**
 * Initialize map canvas, show a map, and left panel, allow use to create a trip.
 * @return
 */
function initializeCanvas() {
	// show a map
	var latlng = new google.maps.LatLng(59.33034085241191, 18.06255340576172);
	var myOptions = {
		zoom : constMinZoom,
		center : latlng,
		mapTypeControl : false,
		streetViewControl : false,
		disableDoubleClickZoom : true,
		navigationControlOptions : {
			position : google.maps.ControlPosition.RIGHT
		},
		mapTypeId : google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	geocoder = new google.maps.Geocoder();

//	jQuery.post("/map/getinfo", null,
//		function (returnJson) {
//			renderInfo(returnJson.info);
//			render(returnJson.map);
//			
//			jQuery("[id*=editPlaceMark]").hide();
//			
//			jQuery("#show").live('click', function() {				
//				formId = this.parentNode.id;
//				var lat = jQuery("[id=" + formId + "] #lat").val();
//				var lng = jQuery("[id=" + formId + "] #lng").val();
//				jQuery("[id*=editPlaceMark]").hide();
//				jQuery("[id=editPlaceMark" + lat + "-" + lng + "]").show();
//				
//			});
//			
//			// show save placemark link 
//			jQuery('#savePlaceMark').live('click', function() {
//				formId = this.parentNode.id;
//				var lat = jQuery("[id=" + formId + "] #lat").val();
//				var lng = jQuery("[id=" + formId + "] #lng").val();
//				jQuery.post("/map/editplacemark/", 
//					{
//						"lat" : lat,
//						"lng" : lng,
//						"name" : jQuery("[id=" + formId + "] #name").val(),
//						"description" : jQuery("[id=" + formId + "] #description").val()
//					}, 
//					function(returnJson) {
//						render(returnJson.map);
//						renderInfo(returnJson.info);
//						jQuery("[id*=editPlaceMark]").hide();
//					},
//					"json"
//				);
//			});
//		},
//		"json"
//	);
	google.maps.event.addListener(map, 'dragend', function(event){
		// Timer here is to avoid constant refreshing Panoramio
		// when user moves the map continuously
		clearTimeout(panoramioWaitTimerID);
		panoramioWaitTimerID = setTimeout(fetchPanoramio, 2000);
	});
	google.maps.event.addListener(map, 'zoom_changed', function(event){
		var zoom = map.getZoom();
		if (zoom < constMinZoom) {
			map.setZoom(constMinZoom);
		}
		clearTimeout(panoramioWaitTimerID);
		panoramioWaitTimerID = setTimeout(fetchPanoramio, 2000);
	});
	
}

/**
 * Fetch panoramio data, render them on the map in callback function.
 * 
 * @return
 */
function fetchPanoramio() {
	latLngBounds = map.getBounds();
	var northEast = latLngBounds.getNorthEast();
	var southWest = latLngBounds.getSouthWest();
	jQuery.ajax({
		   type: "GET",
		   url: "http://www.panoramio.com/map/get_panoramas.php",
		   data: "set=public&from=0&to=20&minx=" + southWest.lng() + "&miny=" + southWest.lat() + "&maxx=" + northEast.lng() + "&maxy=" + northEast.lat() + "&size=mini_square&mapfilter=true",
		   success: function(data){
		     renderPanoramio(data["photos"]);
		   },
		   dataType : "jsonp"
		 });
}

function initialize() {
	var latlng = new google.maps.LatLng(59.33034085241191, 18.06255340576172);
	var myOptions = {
		zoom : 4,
		center : latlng,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	google.maps.event.addListener(map, 'click', function(event) {
		placeMarker(event.latLng, index);
	});
	
}

/**
 * Add place marker. Right click to remove it.
 */
function placeMarker(location, index) {
	var marker = new google.maps.Marker( {
		position : location,
		map : map
	});

	google.maps.event.addListener(marker, 'click', function(event) {
		var contentString = marker.getPosition().ra + ", "
				+ marker.getPosition().sa + "<br/>"
				+ "<div id='lat' style='display:none'>"
				+ marker.getPosition().ra + "</div>"
				+ "<div id='lng' style='display:none'>"
				+ marker.getPosition().sa + "</div>"
				+ "<div id='addPlaceMark'>Add to placemark</div>";
		var infowindow = new google.maps.InfoWindow( {
			content : contentString
		});
		infowindow.open(map, marker);
	});

	map.setCenter(location);

	markersArray.push(marker);
	var pos = marker.getPosition();
//	jQuery.post("/map/prepareplacemark", {
//		'lat' : pos.lat(),
//		'lng' : pos.lng()
//	}, function(returnJson) {
//		//render(returnJson.map);
//		renderInfo(returnJson.info);
//		jQuery("[id*=editPlaceMark]").hide();
//	}, "json");
	
}

/**
 * Reset.
 */
function reset() {
	jQuery.post("/map/reset", null, function(returnJson) {
		if (markersArray) {
			for (i in markersArray) {
				markersArray[i].setMap(null);
			}
		}
		if (panoramioArray) {
			for (i in panoramioArray) {
				panoramioArray[i].setMap(null);
			}
		}
		
		
		renderInfo(returnJson.info);
		render(returnJson.map);
		initializeCanvas();
	}, "json");
}

/**
 * Render panoramio data on map.
 * 
 * @param data
 * @return
 */
function renderPanoramio(data) {
	/*if (markersArray) {
		for (i in markersArray) {
			markersArray[i].setMap(null);
		}
	}*/
	
	// Remove old panoramia pictures
	if (panoramioArray) {
		for (i in panoramioArray) {
			panoramioArray[i].setMap(null);
		}
	}
	
	// Render new panoramia pictures.
	if (data) {
		for (var i = 0; i < data.length; i++) {
			var location = new google.maps.LatLng(data[i]["latitude"],
					data[i]["longitude"]);
		    var marker = new google.maps.Marker({
		        position: location, 
		        map: map,
		        icon: data[i]["photo_file_url"]
		    });
		    panoramioArray[i] = marker;
		    attachMessage(marker, data[i]);
	    }
	}
}

/**
 * Render panoramio window info.
 * 
 * @param marker
 * @param panoramioData
 * @return
 */
function attachMessage(marker, panoramioData) {
	var temp = panoramioData["photo_file_url"];
	var imgUrl = temp.replace("mini_square", "small");
	var contentString = "<div class='infoWindow'>" + panoramioData["photo_title"] 
        + "</div><br/><img src=\"" + imgUrl + "\"></img><br/>"
        + "<a href=\"javascript:void(0);\" onclick=\"addPlaceMark('" + panoramioData["latitude"] + "', '" + panoramioData["longitude"] + "', '" + panoramioData["photo_title"] + "', '" + panoramioData["photo_file_url"] + "')\">Add to placemark</a>";
	  var infowindow = new google.maps.InfoWindow(
	      { content: contentString,
	    	pixelOffset : {width : 0, height : 0}
	      });
	  
	  google.maps.event.addListener(marker, 'click', function() {
		if ( currentInfoWindow )
			currentInfoWindow.close();
	    infowindow.open(map,marker);
	    currentInfoWindow = infowindow;
	  });
}

/**
 * Add one image to placemakr.
 * 
 * @param data panoramio data
 * @return
 */
function addPlaceMark(latitude, longitude, photo_title, photo_file_url) {
	jQuery.post(
			"/map/addplacemark",
			{
				"lat" : latitude,
				"lng" : longitude,
				"name" : photo_title,
				"fileUrl" : photo_file_url
			},
			function(returnJson) {
				renderInfo(returnJson["info"]);
			    jQuery("[id*=editPlaceMark]").hide();
			},
			"json"
	);
}

function renderAttractionView() {
	jQuery('#attractionView').empty().append(mapInfo);
}

/**
 * Render all markers on map.
 */
function render(markers) {
	if (markersArray) {
		for (i in markersArray) {
			markersArray[i].setMap(null);
		}
	}
	
	if (markers) {
		for (i in markers) {
			var location = new google.maps.LatLng(markers[i].latitude,
					markers[i].longitude);
			var marker = new google.maps.Marker( {
				position : location,
				map : map
			});
			marker.setMap(map);
			markersArray.push(marker);
		}
	}
}

/**
 * Edit placemark.
 * 
 * @param lat
 * @param lng
 * @return
 */
function editPlaceMark(lat, lng) {
	jQuery.post(
		"/map/editplacemark", 
		{
			"lat" : lat,
			"lng" : lng
		}, 
		function(returnJson) {
		if (markersArray) {
			for (i in markersArray) {
				markersArray[i].setMap(null);
			}
		}
		//render(returnJson.map);
		//renderInfo(returnJson.info);
		jQuery("[id*=editPlaceMark]").hide();
	}, "json");
}

/**
 * Remove place mark from map.
 * 
 * @param lat
 * @param lng
 * @return
 */
function removePlaceMark(lat, lng) {
	jQuery.post(
		"/map/removeplacemark", 
		{
			"lat" : lat,
			"lng" : lng
		}, 
		function(returnJson) {
		render(returnJson.map);
		renderInfo(returnJson.info);
//		jQuery("[id*=editPlaceMark]").hide();
	}, "json");
}

function renderInfo(mapInfo) {
    jQuery('#mapInfo').empty().append(mapInfo);
}

/**
 * Create trip.
 * @return
 */
function createTrip() {
	var title = jQuery('#createTrip #title').val();
	var description = jQuery('#createTrip #description').val();
	jQuery.post(
		"/map/createtrip", 
		{
			"title" : title,
			"description" : description,
			"public" : 1,
			"step" : 1
		}, 
		function(returnJson) {
			render(returnJson.map);
			renderInfo(returnJson.info);
			initialize();
		},
		"json");
}

function findAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode({
      'address': address,
      'partialmatch': true}, geocodeResult);
}

function geocodeResult(results, status) {
  if (status == 'OK' && results.length > 0) {
    map.fitBounds(results[0].geometry.viewport);
  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
}


jQuery("[id*=editPlaceMark]").hide();
jQuery("#show").live('click', function() {				
	formId = this.parentNode.id;
	var lat = jQuery("[id=" + formId + "] #lat").val();
	var lng = jQuery("[id=" + formId + "] #lng").val();
	jQuery("[id*=editPlaceMark]").hide();
	jQuery("[id=editPlaceMark" + lat + "-" + lng + "]").show();
	
});